package cn.itcast.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author mrchen
 * @date 2022/6/13 10:20
 */
//@Order(-1)
//@Component
public class AuthorizeFilter implements GlobalFilter {
    /**
     * 过滤方法
     * @param exchange  请求上下文   包含: request   response
     * @param chain   过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1. 获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        // 2. 获取请求参数: authorization  的值   路径?authorization=admin
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        String authorization = queryParams.getFirst("authorization");
        // 3. 判断是否等于 admin
        if("admin".equals(authorization)){
            // 4. 如果等于admin 放行请求  注意:不要忘记加return
            return chain.filter(exchange);
        }
        // 5. 如果不等于admin  终止请求
        ServerHttpResponse response = exchange.getResponse();
        // 设置状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        // 终止请求
        return response.setComplete();
    }
}
